package com.ch.dream.logic.shortstory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import cn.goso.utility.NumberTools;
import cn.goso.utility.StringTools;

import com.ch.dream.R;
import com.ch.dream.activity.shortstory.StoryContentActivity;
import com.ch.dream.activity.shortstory.TimeInputActivity;
import com.ch.dream.asynctask.AddStoryModifyRequestAsyncTask;
import com.ch.dream.asynctask.AddStoryTimeRequestAsyncTask;
import com.ch.dream.asynctask.GetTimeRecommendRequestAsyncTask;
import com.ch.dream.base.BaseLogic;
import com.ch.dream.base.BaseRequestAsyncTask.RequestServerListener;
import com.ch.dream.bean.StorymodifyBean;
import com.ch.dream.bean.StorytimeBean;
import com.ch.dream.common.CommonData;
import com.ch.dream.common.CommonResult;
import com.ch.dream.common.CommonUserInfo;
import com.ch.dream.net.MyHttpAPI;
import com.ch.dream.tools.UtilTools;
import com.ch.dream.tools.ViewTools;

public class TimeInputLogic extends BaseLogic {

	public TimeInputLogic(TimeInputActivity activity) {
		super(activity);
	}
	public TimeInputLogic(TimeInputActivity activity,int layoutId) {
		super(activity,layoutId);
	}
	
	private Spinner spStoryType;//故事类型选择
	private RelativeLayout rlStoryModify;//故事修饰词选布局
	private RelativeLayout rlStoryAddModify;//故事修饰词添加布局
	private Spinner spStoryModify;//故事修饰词选择
	private Button btModify;//故事修饰词添加
	private EditText etAddModify;//故事修饰词
	private EditText etTime;//故事时间
	private Button btAddModify;//故事修饰词添加
	private Button btCancelModify;//取消按钮
	private ListView lvRecommend;//推荐列表
	List<String> listModify;
	List<String> listRecommend;
	ArrayAdapter<String> saModify;
	private StorymodifyBean storymodifyBean;
	private StorytimeBean storytimeBean;
	private String modifyType ="1";
	
	public void initViews(){
		spStoryType =(Spinner)activity.findViewById(R.id.spStoryType);
		spStoryModify =(Spinner)activity.findViewById(R.id.spStoryModify);
		ViewTools.setSpinnerBg(spStoryType, 200, 60);
		ViewTools.setSpinnerBg(spStoryModify, 200, 60);
		btModify = (Button)activity.findViewById(R.id.btModify);
		rlStoryModify = (RelativeLayout)activity.findViewById(R.id.rlModify);
		rlStoryAddModify = (RelativeLayout)activity.findViewById(R.id.rlAddModify);
		etAddModify =  (EditText)activity.findViewById(R.id.etAddModify);
		btAddModify = (Button)activity.findViewById(R.id.btAddModify);
		etTime = (EditText)activity.findViewById(R.id.etTime);
		btCancelModify =(Button)activity.findViewById(R.id.btCancelModify);
		lvRecommend = (ListView)activity.findViewById(R.id.lvRecommend);
	}
	
	
	public void init() throws Exception{
		myHttpApi = new MyHttpAPI();
		initViews();
		initRecommendList();
		initModifyAndType();
	}
	/**
	 * 初始化修饰词与类型
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void initModifyAndType() throws Exception{
		btModify.setVisibility(View.GONE);
		if(CommonUserInfo.userId!=null && !CommonUserInfo.userId.equals("")){
			btModify.setVisibility(View.VISIBLE);
		}
		btModify.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				rlStoryModify.setVisibility(View.GONE);
				rlStoryAddModify.setVisibility(View.VISIBLE);
				etAddModify.requestFocus();
			}
		});
		
		btAddModify.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try{
					if(!validateModify()){
						return;
					}
					progressDialog = ViewTools.showLoading(activity,"保存修饰词", CommonData.LOADINGMESSAGE);
					storymodifyBean =new StorymodifyBean();
					String modifyName = etAddModify.getText().toString();
					storymodifyBean.setCreator(NumberTools.stringToInt(CommonUserInfo.userId));
					storymodifyBean.setModifyType(1);
					storymodifyBean.setModifyName(modifyName);
					new AddStoryModifyRequestAsyncTask(activity, new RequestServerListener() {
						@Override
						public void onRequestServerEnd(Object result) {
							HashMap<String, Object> map =new HashMap<String, Object>();
							map.put("id", storymodifyBean.getId());
							map.put("modifyName", storymodifyBean.getModifyName());
							map.put("modifyType", storymodifyBean.getModifyType());
							saModify.insert(etAddModify.getText().toString(),0);
							rlStoryModify.setVisibility(View.VISIBLE);
							rlStoryAddModify.setVisibility(View.GONE);
							etAddModify.setText("");
							etTime.requestFocus();
							JSONObject jsonObject = (JSONObject)result;
							try{
								map.put("id",jsonObject.get("id"));
								CommonData.storyModifyIdList.add(0,jsonObject.get("id").toString());
							}catch (Exception e) {
								map.put("id","0");
								e.printStackTrace();
							}
							CommonData.storyModifyList.add(0, map);
							spStoryModify.setSelection(0);
							progressDialog.dismiss();
						}
						
						@Override
						public void onRequestServerBegin() {
							
						}
					}).execute(storymodifyBean);
					
				}catch (Exception e) {
					progressDialog.dismiss();
					ViewTools.showShortToast(activity, "网络错误");
					e.printStackTrace();
				}
			}
		});
		btCancelModify.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				rlStoryModify.setVisibility(View.VISIBLE);
				rlStoryAddModify.setVisibility(View.GONE);
				etAddModify.setText("");
				etTime.requestFocus();
			}
		});
		if(CommonData.storyTypeList==null){
			UtilTools.requestStoryType(activity,spStoryType);
		}else{
			listModify =new ArrayList<String>();
			for(int i=0;i<CommonData.storyTypeList.size();i++){
				listModify.add(CommonData.storyTypeList.get(i).get("typeName").toString());
			}
			saModify = new ArrayAdapter<String>(CommonData.currentActivity,R.layout.spinner_item,listModify){
				@Override
				public long getItemId(int position) {
					return NumberTools.stringToInt(CommonData.storyTypeList.get(position).get("id").toString());
				}
			};
			saModify.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spStoryType.setAdapter(saModify);
		}
		
		if(CommonData.storyModifyList==null){
			UtilTools.requestStoryModify(activity,spStoryModify,modifyType);
			saModify = (ArrayAdapter<String>)spStoryType.getAdapter();
		}else{
			saModify = new ArrayAdapter<String>(CommonData.currentActivity,R.layout.spinner_item,UtilTools.setStoryModifyType(modifyType)){
				@Override
				public long getItemId(int position) {
					return NumberTools.stringToInt(CommonData.storyModifyIdList.get(position));
				}
			};
			saModify.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spStoryModify.setAdapter(saModify);
		}
	}
	
	/**
	 * 初始化推荐列表
	 */
	public void initRecommendList(){
		if(CommonData.timeRecommendList==null || CommonData.timeRecommendList.size()==0){
			new GetTimeRecommendRequestAsyncTask(activity, new RequestServerListener() {
				@Override
				public void onRequestServerEnd(Object result) {
					CommonData.timeRecommendList = UtilTools.getRecommendList((JSONArray)result);
					ListAdapter adapter = new SimpleAdapter(activity,CommonData.timeRecommendList,R.layout.s_recommend_list_item,
							new String[]{"recommend"},new int[]{R.id.recommend}){
						@Override
						public View getView(int position, View convertView,
								ViewGroup parent) {
							View viewHolder = super.getView(position, convertView, parent);
							if(position==0){
								viewHolder.setBackgroundResource(R.drawable.selector_item_top);
							}
							if(position==CommonData.timeRecommendList.size()-1){
								viewHolder.setBackgroundResource(R.drawable.selector_item_bottom);
							}
							return viewHolder;
						}
					};
					lvRecommend.setAdapter(adapter);
				}
				
				@Override
				public void onRequestServerBegin() {
					
				}
			}).execute(new Object());
		}else{
			ListAdapter adapter = new SimpleAdapter(activity,CommonData.timeRecommendList,R.layout.s_recommend_list_item,
					new String[]{"recommend"},new int[]{R.id.recommend}){
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View viewHolder = super.getView(position, convertView, parent);
					if(position==0){
						viewHolder.setBackgroundResource(R.drawable.selector_item_top);
					}
					if(position==CommonData.timeRecommendList.size()-1){
						viewHolder.setBackgroundResource(R.drawable.selector_item_bottom);
					}
					return viewHolder;
				}
			};
			lvRecommend.setAdapter(adapter);
		}
		lvRecommend.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> data, View view, int position,
					long id) {
				String text  = CommonData.timeRecommendList.get(position).get("recommend").toString();
				etTime.setText(text);
				etTime.setSelection(text.length());
			}
		});
		
	}
	
	/**
	 * 验证添加修饰词输入
	 * @return
	 */
	private boolean validateModify(){
		String time = etAddModify.getText().toString();
		if(StringTools.isEmpty(time)){
			ViewTools.showShortToast(activity, "请输入修饰词");
			return false;
		}
		
		if(time.length()>10){
			ViewTools.showShortToast(activity, "修饰词不能超过10个字符");
			return false;
		}
		return true;
	}
	
	/**
	 * 验证添加时间输入
	 * @return
	 */
	private boolean validateTime(){
		String time = etTime.getText().toString();
		if(StringTools.isEmpty(time)){
			ViewTools.showShortToast(activity, "请输入要创造的时间");
			return false;
		}
		if(time.length()<5){
			ViewTools.showShortToast(activity, "创造的时间必须超过4个字符");
			return false;
		}
		if(time.length()>20){
			ViewTools.showShortToast(activity, "创造的时间不能超过20个字符");
			return false;
		}
		return true;
	}
	
	/**
	 * 提交时间
	 */
	public void submit(){
		if(!validateTime()){
			return;
		}
		storytimeBean =new StorytimeBean();
		int modifyId = (int)spStoryModify.getSelectedItemId();
		int typeId = (int)spStoryType.getSelectedItemId();
		storytimeBean.setStoryModifyId(modifyId);
		storytimeBean.setStoryTime(etTime.getText().toString());
		storytimeBean.setStoryTypeId(typeId);
		storytimeBean.setUserId(NumberTools.stringToInt(CommonUserInfo.userId));
		storytimeBean.setCreateTime(CommonData.IMEI);
		try{
			progressDialog = ViewTools.showLoading(activity,"创造时间", CommonData.LOADINGMESSAGE);
			
			new AddStoryTimeRequestAsyncTask(activity, new RequestServerListener() {
				
				@Override
				public void onRequestServerEnd(Object result) {
					try{
						if(result!=null && ((JSONObject)result).get("result").equals(CommonResult.SUCCESS)){
							JSONObject jsonResult =(JSONObject)result;
							Intent intent =new Intent();
							intent.putExtra("content", jsonResult.getString("story"));
							intent.putExtra("storyId",  jsonResult.getString("storyId"));
							intent.setClass(activity, StoryContentActivity.class);
//							int replyNum = UtilTools.getIntSharedPreferences(activity,CommonData.REPLYNUM, "timeNum", 0);
//							replyNum = replyNum-1;
//							UtilTools.setIntSharedPreferences(activity,CommonData.REPLYNUM, "timeNum", replyNum);
							activity.startActivity(intent);
							activity.finish();
						}else if(result!=null && ((JSONObject)result).getString("result").equals(CommonResult.FAIL)){
							if(activity == CommonData.currentActivity){
								ViewTools.showMessage(CommonData.currentActivity,  ((JSONObject)result).getString("message"));
							}
						}
					}
					catch (Exception e) {
						ViewTools.showShortToast(activity, "网络错误");
						progressDialog.dismiss();
						e.printStackTrace();
					}
					progressDialog.dismiss();
				}
				
				@Override
				public void onRequestServerBegin() {
					
				}
			}).execute(storytimeBean);
			
		}catch (Exception e) {
			progressDialog.dismiss();
			ViewTools.showShortToast(activity, "网络错误");
			e.printStackTrace();
		}
		
	}
}
